#include "../inc/VideoPlayer.h"
#include <iostream>
#include <fstream>

VideoPlayer::VideoPlayer(const std::string& playerPath) 
    : m_playerPath(playerPath), m_playerPid(-1), m_isPlaying(false)
{
    // 检查播放器是否存在
    std::ifstream file(m_playerPath);
    if (!file.good())
    {
        std::cerr << "Error: Player not found at " << m_playerPath << std::endl;
    }
}

VideoPlayer::~VideoPlayer()
{
    stop();  // 确保析构时停止播放
}

bool VideoPlayer::play(const std::string& filePath)
{
    // 停止当前播放
    if (m_isPlaying)
    {
        stop();
    }

    // 检查视频文件是否存在
    std::ifstream file(filePath);
    if (!file.good())
    {
        std::cerr << "Error: Video file not found: " << filePath << std::endl;
        return false;
    }

    // 创建子进程播放视频（启用视频输出驱动 -vo xv）
    pid_t pid = fork();
    if (pid == 0)
    {
        // 子进程：执行 mplayer 并显示视频画面
        execl(m_playerPath.c_str(), "mplayer", "-vo", "fbdev2", filePath.c_str(), (char*)NULL);
        std::cerr << "Failed to launch video player!" << std::endl;
        exit(1);
    }
    else if (pid > 0)
    {
        // 父进程：记录进程ID和状态
        m_playerPid = pid;
        m_isPlaying = true;
        return true;
    }
    else
    {
        std::cerr << "Failed to fork process!" << std::endl;
        return false;
    }
}

void VideoPlayer::stop()
{
    if (m_isPlaying && m_playerPid > 0)
    {
        kill(m_playerPid, SIGTERM);  // 终止进程
        waitpid(m_playerPid, nullptr, 0);
        m_playerPid = -1;
        m_isPlaying = false;
    }
}

void VideoPlayer::pause()
{
    if (m_isPlaying && m_playerPid > 0)
    {
        kill(m_playerPid, SIGSTOP);  // 暂停进程
    }
}

void VideoPlayer::resume()
{
    if (m_isPlaying && m_playerPid > 0)
    {
        kill(m_playerPid, SIGCONT);  // 恢复进程
    }
}

bool VideoPlayer::isPlaying() const
{
    return m_isPlaying;
}



// int main()
// {
//     VideoPlayer player("/usr/bin/mplayer");  // 指定 mplayer 路径

//     // 播放视频（需替换为实际路径）
//     if (player.play("test.mp4"))
//     {
//         std::cout << "Playing video..." << std::endl;
//         sleep(5);  // 播放5秒

//         player.pause();// 暂停播放
//         std::cout << "Paused." << std::endl;
//         sleep(2);

//         player.resume();// 恢复播放
//         std::cout << "Resumed." << std::endl;
//         sleep(5);

//         player.stop();// 停止播放
//         std::cout << "Stopped." << std::endl;
//     }
//     else
//     {
//         std::cerr << "Failed to play video!" << std::endl;
//     }

//     return 0;
// }